import _ from 'lodash';
import { message } from 'antd';
import {
    getGameDict,
    getGameStore,
    updateGameStore,
} from '../../services/store';

export default {
    namespace: 'game',
    state: {
        data: [],
        base: [],
    },
    subscriptions: {
        setup(args) {
            const { dispatch, history } = args;
            history.listen(({ pathname }) => {
                if (pathname === '/store/game') {
                    dispatch({
                        type: 'init',
                    });
                }
            });
        }
    },
    effects: {
        * init(payload, { put }) {
            yield put({
                type: 'load',
            });
        },
        * load(payload, { put, call, select }) {
            // todo 需要获得游戏的基础数据, 这里用 GAMES 暂时代替游戏的基础数据
            // todo data 为店铺自己的游戏数据, 对基础数据的映射
            const { code: dictCode, data: base } = yield call(getGameDict);
            const { storeId } = yield select((state => state.app.user));
            const { data, code } = yield call(getGameStore, storeId);
            if (dictCode === '0000' && !_.isEmpty(base)) {
                if (code === '0000') {
                    const target = _.map(data, ({ id }) => {
                        const inDict = _.find(base, ['id', id]);
                        if (inDict) {
                            return id.toString();
                        }
                    });
                    yield put({
                        type: 'upState',
                        payload: {
                            data: _.compact(target),
                            base,
                        },
                    });
                } else {
                    message.warning('本店游戏列表请求失败');
                }
            } else {
                message.warning('游戏基础数据列表请求失败');
            }
        },
        * submit(payload, { select, call }) {
            const { data: ids } = yield select(({ game }) => game);
            const { storeId } = yield select((state => state.app.user));
            const { code, err } = yield call(updateGameStore, { storeId, ids: _.join(ids, ',') });
            if (code === '0000') {
                message.success('更新成功!');
            } else {
                message.error(`${err}, 更新失败!`);
            }
        },
    },
    reducers: {
        upState(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
    }
};
